package com.mfcxy.home.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.mfcxy.entity.Type;
import com.mfcxy.service.IBlogSerivce;
import com.mfcxy.service.ICommentsService;
import com.mfcxy.service.ITypeService;
import com.mfcxy.tools.BackJson;

@Controller
public class HomeController {
	
	@Autowired
	private IBlogSerivce blogSerivce;
	
	@Autowired
	private ITypeService typeService;
	
	@Autowired
	private ICommentsService commentsService;
	
	
	/**
	 * 首页
	 * @param p
	 * @param model
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@RequestMapping("/")
	public String home(@RequestParam(name = "p" , defaultValue = "1") int p , Model model) throws JsonParseException, JsonMappingException, IOException {
		model.addAttribute("map", blogSerivce.selectlistNum(p));
		return "/home/home_home";
	}
	
	/**
	 * 文章内容
	 * 
	 * 如你想要读取该记录的上一条和下一条记录
	 * 则可以使用如下sql 来处理该问题
	 * 
	 * SELECT * FROM mfcxy_blog WHERE id = #{id} #这条sql 读取当前数据
	 * SELECT * FROM mfcxy_blog WHERE id < #{id} ORDER BY id DESC LIMIT 1    #读取上一条数据
	 * SELECT * FROM mfcxy_blog WHERE id > #{id} ORDER BY id  LIMIT 1    #读取下一条数据
	 * 
	 * @return
	 */
	@RequestMapping("/detail/{id}")
	public String detail(@PathVariable int id , Model model) {
		//文章内容
		model.addAttribute("blog", blogSerivce.getById(id));
		//该文章的评论总数
		model.addAttribute("commentNum", commentsService.getCountByBid(id));
		model.addAttribute("comments", commentsService.selectlist(1, id));
		return "home/home_detail";
	}
	
	/**
	 *  获取分类信息
	 * @param pid
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/gettype")
	public BackJson getType(@RequestParam(name = "pid" , defaultValue = "0") int pid) {
		BackJson bj = new BackJson();
		Map<String, Object> map = new HashMap<>();
		map.put("list", typeService.listById(pid));
		bj.setCode(1);
		bj.setData(map);
		return bj;
	}
	
	/**
	 *  获取分类信息
	 * @param pid
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/gettypetest")
	public BackJson getTypetest(@RequestParam(name = "pid" , defaultValue = "0") int pid) {
		BackJson bj = new BackJson();
		Map<String, Object> map = new HashMap<>();
		map.put("list", typeService.listByIdTest(pid));
		bj.setCode(1);
		bj.setData(map);
		return bj;
	}
	
	/**
	 * 搜索
	 * @return
	 */
	@RequestMapping("/search")
	public String search() {
		return "home/home_search";
	}
}
